<?php

class multitender_model_firm extends multitender_model {

    function  __construct() {
        parent::__construct();
        $this->db      = & $this->conf['dbs']['person'];
    }

    function save($arr) {
        if (is_null($this->db)) {
            return false;
        }

        if ($id=$this->check($arr['user_id'])) {
            // FIXME: update by id, not user_id. And where is index?
            $sql="UPDATE firms SET name=?,
                                   INN=?,
                                   KPP=?,
                                   domicile_index=?,
                                   domicile_region=?,
                                   domicile_town=?,
                                   domicile=?,
                                   address_index=?,
                                   address_region=?,
                                   address_town=?,
                                   address=?,
                                   telephone=?,
                                   contact=?
                                   WHERE user_id=?";
        } else {
            $sql="INSERT INTO firms(name,
                                    INN,
                                    KPP,
                                    domicile_index,
                                    domicile_region,
                                    domicile_town,
                                    domicile,
                                    address_index,
                                    address_region,
                                    address_town,
                                    address,
                                    telephone,
                                    contact,
                                    user_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        }
        if ($this->db->Execute($sql, array(
        $arr['name'],
        $arr['INN'],
        $arr['KPP'],
        $arr['domicile_index'],
        $arr['domicile_region'],
        $arr['domicile_town'],
        $arr['domicile'],
        $arr['address_index'],
        $arr['address_region'],
        $arr['address_town'],
        $arr['address'],
        $arr['telephone'],
        $arr['contact'],
        $arr['user_id']))) {
            return true;
        } else {
            return false;
        }
    }

    function load($user_id) {
        if (is_null($this->db)) {
            return false;
        }

        $sql="SELECT * FROM firms WHERE user_id=$user_id LIMIT 1";
        $arr=$this->db->GetRow($sql);
        if ($arr) {
            return $arr;
        } else {
            return false;
        }
    }

    function list_firm() {
        if (is_null($this->db)) {
            return false;
        }

        $sql="SELECT * FROM firms";
        $list=$this->db->GetAll($sql);
        if ($list) {
            return $list;
        } else {
            return false;
        }
    }

    function check($user_id) {
        if (is_null($this->db)) {
            return false;
        }

        $sql="SELECT id FROM firms WHERE user_id=$user_id";
        if ($id=$this->db->GetOne($sql)) {
            return $id;
        } else {
            return false;
        }
    }


    /**
     * Проверка и очистка данных с формы "реквизиты организации"
     * передача по ссылке
     * @param  array $form_array
     * @return boolen
     */
    public function validate_firm(array &$form_array) {
        foreach ($form_array as &$val) {
            $val = $this->clear_address_part($val);
            if (empty($val)) {
                $val = null;
            } else {
                $val = strip_tags($val);
            }
        }

        if (empty($form_array['name']) ||
                empty($form_array['INN']) ||
                empty($form_array['telephone']) ||
                empty($form_array['contact']) ||
                empty($form_array['domicile_index']) ||
                empty($form_array['domicile_region']) ||
                empty($form_array['domicile_town']) ||
                empty($form_array['domicile'])) {
            return false;
        }

        if (empty($form_array['addom']) && (
                empty($form_array['address_index']) ||
                        empty($form_array['address_region']) ||
                        empty($form_array['address_town']) ||
                        empty($form_array['address']))) {
            return false;
        }

        if ( isset($form_array['addom']) ) {
            $form_array['address_index']   = NULL;
            $form_array['address_region']  = NULL;
            $form_array['address_town']    = NULL;
            $form_array['address']         = NULL;
        }

        return true;
    }

    /**
     * Загружает данные и обрабатывает их
     * @param int $user_id
     * @return array
     */
    public function load_prepared($user_id) {
        $firm = $this->load($user_id);
        return $firm ? $this->prepare_firm($firm) : null;
    }

    /**
     * Добавляет в массив полные адреса
     * @param array $firm_array
     * @return array
     */
    public function prepare_firm(array $firm_array) {
        $firm_array['domicile_full'] = $this->create_address(array(
                $firm_array['domicile_index'],
                $firm_array['domicile_region'],
                $firm_array['domicile_town'],
                $firm_array['domicile']));
        $firm_array['address_full'] = $this->create_address(array(
                $firm_array['address_index'],
                $firm_array['address_region'],
                $firm_array['address_town'],
                $firm_array['address']));
        return $firm_array;
    }


    /**
     * Создает полный адрес из кусочков, поданных через массив
     * Проверяет, очишает и делает прочую грязную работу
     * @param array $address_parts
     * @param string $delimetr
     * @return string
     */
    public function create_address(array $address_parts, $delimetr = ', ') {
        $return = '';
        foreach ($address_parts as $part) {
            $part = $this->clear_address_part($part);
            if ($part) {
                $return .= $delimetr . $part;
            }
        }

        $return = substr($return, strlen($delimetr));
        $return = $this->clear_address_part($return);

        return $return ? $return : null;
    }

    /**
     * Очистка от мусора
     * @param array $address_part
     * @return string
     */
    private function clear_address_part($address_part) {
        return preg_replace(array('/^[.,\s]+/', '/[.,\s]+$/'), '', $address_part);
    }

}
